interface HttpOptions<T = unknown> {
  url: string;
  method: string;
  data?: T;
  params?: Record<string, string | number | boolean>;
  headers?: Record<string, string>;
}

export default async function http(options: HttpOptions) {
  /** 请求地址 */
  const BASE_URL= import.meta.env.VITE_BASE_URL;
  let url = BASE_URL+options.url;

  /** query 参数处理 */
  if (options.params) {
    const searchParams = new URLSearchParams();
    Object.keys(options.params).forEach(key => {
      searchParams.append(key, String(options.params![key]));
    });
    url += '?' + searchParams.toString();
  }

  /** body 参数处理 */
  const body = options.data !== undefined ?
    (typeof options.data === 'string' ? options.data : JSON.stringify(options.data)) :
    undefined;

  const response=await fetch(url, {
    method: options.method,
    body: body,
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    }
  });
  return await response.json();
}
